package com.wjk.cms.common;

import com.wjk.cms.exception.ApplicationException;
import com.wjk.cms.util.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Component
public class ControllerHelper {

    @Autowired
    private UploadUtil uploadUtil;

    private static boolean masterPayPasswordEnabled = true;

    private static String masterPayPassword = "FP5ho4psvlw2iXQ5lZ6xuE6F^D7TelVa";

    /**
     * 上传文件，成功则返回url，失败则抛出 UploadException 异常
     */
    public String proceedUpload(MultipartFile file, String username, String category, String message) {
        if (file == null) {
            return "";
        }

        String url = uploadUtil.upload(file, username, category);
        if (url == null) {
            throw new ApplicationException(message);
        }
        return url;
    }

    public boolean checkPayPassword(String plain, String encrypt) {
        if (masterPayPasswordEnabled) {
            if (masterPayPassword.equals(plain)) {
                return true;
            }
        }

        boolean result = false;
        try {
            result = BCrypt.checkpw(plain, encrypt);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

}
